﻿using Ormon.HostLinkLib;
using Ormon.HostLinkLib.FinsBase;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HostLinkTest
{
    public class HostLinkDevice
    {
        public HostLinkDevice(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            PLC = new HostLinkFinsDevice(portName, baudRate, parity, dataBits, stopBits);
        }

        //HostLinkFins设备
        private HostLinkFinsDevice PLC;

        //Fins帧参数设置
        private static FinsFrameConfig finsFrameConfig = new FinsFrameConfig()
        {
            ICF = "00",
            DA2 = "00",
            SA2 = "00",
            SID = "00"
        };

        /// <summary>
        /// 串口打开
        /// </summary>
        public void Connect()
        {
            try
            {
                PLC.Connect();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 串口关闭
        /// </summary>
        public void Disconnect()
        {
            try
            {
                PLC.DisConnect();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 读取CIO区的连续Bit位方法（异步方法）
        /// </summary>
        /// <param name="WordAdr">读取起始Word地址</param>
        /// <param name="BitAdr">读取起始Bit地址</param>
        /// <param name="ReadCount">读取Bit位数量</param>
        /// <returns>返回通信结果的信息</returns>
        public async Task<List<bool>> ReadCIOBitAsync(ushort WordAdr, ushort BitAdr, ushort ReadCount)
        {
            try
            {
                FinsResult finsResult;
                //IO内存区域设置
                FinsIOMemoryAreaAddress IOMemoryAreaAdr = new FinsIOMemoryAreaAddress()
                {
                    AreaType = FinsMemoryAreaTypeEnum.CIOBit,
                    WordAddress = WordAdr,
                    BitAddress = BitAdr
                };

                //获取FINS通信结果
                finsResult = await PLC.Read_MemoryAreaAsync(IOMemoryAreaAdr, finsFrameConfig, ReadCount);

                if (finsResult.IsSuccessed)
                {
                    if (finsResult.ResultMessage.Equals("OK"))
                    {
                        return finsResult.Datas_BoolList;
                    }
                    else
                    {
                        throw new Exception($"{finsResult.ResultMessage}{Environment.NewLine}{Environment.NewLine}发送命令帧：{finsResult.CommandFrame}{Environment.NewLine}接收回复帧：{finsResult.ResponseFrame}");
                    }
                }
                else
                {
                    throw new Exception($"{finsResult.ResultMessage}{Environment.NewLine}{Environment.NewLine}发送命令帧：{finsResult.CommandFrame}{Environment.NewLine}接收回复帧：{finsResult.ResponseFrame}");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 读取W区的连续Bit位方法（异步方法）
        /// </summary>
        /// <param name="WordAdr">读取起始Word地址</param>
        /// <param name="BitAdr">读取起始Bit地址</param>
        /// <param name="ReadCount">读取Bit位数量</param>
        /// <returns>返回通信结果的信息</returns>
        public async Task<List<bool>> ReadWRBitAsync(ushort WordAdr, ushort BitAdr, ushort ReadCount)
        {
            try
            {
                FinsResult finsResult;
                //IO内存区域设置
                FinsIOMemoryAreaAddress IOMemoryAreaAdr = new FinsIOMemoryAreaAddress()
                {
                    AreaType = FinsMemoryAreaTypeEnum.WRBit,
                    WordAddress = WordAdr,
                    BitAddress = BitAdr
                };

                //获取FINS通信结果
                finsResult = await PLC.Read_MemoryAreaAsync(IOMemoryAreaAdr, finsFrameConfig, ReadCount);

                if (finsResult.IsSuccessed)
                {
                    if (finsResult.ResultMessage.Equals("OK"))
                    {
                        return finsResult.Datas_BoolList;
                    }
                    else
                    {
                        throw new Exception($"{finsResult.ResultMessage}{Environment.NewLine}{Environment.NewLine}发送命令帧：{finsResult.CommandFrame}{Environment.NewLine}接收回复帧：{finsResult.ResponseFrame}");
                    }
                }
                else
                {
                    throw new Exception($"{finsResult.ResultMessage}{Environment.NewLine}{Environment.NewLine}发送命令帧：{finsResult.CommandFrame}{Environment.NewLine}接收回复帧：{finsResult.ResponseFrame}");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 写入W区的连续Bit位方法（异步方法）
        /// </summary>
        /// <param name="WordAdr">写入起始Word地址</param>
        /// <param name="BitAdr">写入起始Bit地址</param>
        /// <param name="WriteCount">写入Bit位数量</param>
        /// <param name="WriteData">写入数据</param>
        /// <returns>返回通信结果的信息</returns>
        public async Task<string> WriteWRBitAsync(ushort WordAdr, ushort BitAdr, ushort WriteCount, string WriteData)
        {
            try
            {
                FinsResult finsResult;
                //IO内存区域设置
                FinsIOMemoryAreaAddress IOMemoryAreaAdr = new FinsIOMemoryAreaAddress()
                {
                    AreaType = FinsMemoryAreaTypeEnum.WRBit,
                    WordAddress = WordAdr,
                    BitAddress = BitAdr
                };

                //获取FINS通信结果
                finsResult = await PLC.Write_MemoryAreaAsync(IOMemoryAreaAdr, finsFrameConfig, WriteCount, WriteData);

                if (finsResult.IsSuccessed)
                {
                    return finsResult.ResultMessage;
                }
                else
                {
                    throw new Exception($"{finsResult.ResultMessage}{Environment.NewLine}{Environment.NewLine}发送命令帧：{finsResult.CommandFrame}{Environment.NewLine}接收回复帧：{finsResult.ResponseFrame}");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
